<?php

class Controller {

	public $ReturnType = '';

	public $G = array();

	public function showMessage($msg, $errCode = 0, $data = array(), $extra = array()) {
		$responseType = strtolower($this->ReturnType);
		if (isset($extra['resType'])) {
			$responseType = $extra['resType'];
		}

		$result = array(
			'errCode' => $errCode,
			'message' => $msg,
			'data' => $data,
		);

		if (isset($extra['jumpURL']) && isset($extra['locationTime'])) {
			$result['jumpURL'] = $extra['jumpURL'];
			$result['locationTime'] = intval($extra['locationTime']);
		}

		switch ($responseType) {
			case 'php':
				echo serialize($result);
				break;
			case 'jsonp':
				header('Content-Type: text/javascript; charset=utf-8');
				$jsCallBackFunc = $_GET['callback'] ?: 'callback';
				if ($extra['callback']) {
					$jsCallBackFunc = $extra['callback'];
				}
				$jsonData = json_encode($result);
				echo $jsCallBackFunc . '(' . $jsonData . ')';
				break;
			case 'return':
				return json_encode($result);
			default:
				header('Content-Type: application/json; charset=utf-8');
				echo json_encode($result);
		}
		exit;
	}

	public function errorMessage($msg, $code = -1, $srvCode = 0, $extra = array(), $data = array()) {
		return $this->showMessage($msg, $code, $data, $extra);
	}

	public function successMessage($msg, $data = array(), $extra = array()) {
		return $this->showMessage($msg, 0, $data, $extra);
	}

	public function template($tpl, $var = null) {
		$view = new View_Discuz();
		if ($var == null) {
			$view->assign($this->G);
		} else {
			$view->assign($var);
		}
		$view->Controller = &$this;
		$view->display($tpl);
	}

}